<template>
  <div>
    <el-upload
        ref="upload"
        list-type="picture-card"
        :action="uploadUrl"
        :headers="headers"
        :before-upload="beforeUpload"
         name="file"
        :limit="limit"
        :on-exceed="handleExceed"
        :on-preview="pictureCardPreview"
        :before-remove="removeFileList"
        :on-success="successUpload"
        :show-file-list="false"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" width="40%" title="图片预览" show-close>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
      <el-dialog top="0vh" width="90%" :visible.sync="isShowCropper" append-to-body>
        <VueCropper
          style="height:800px;margin:5px 0;"
          ref="cropper"
          :img="option.img"
          :outputSize="option.outputSize"
          :outputType="option.outputType"
          :info="option.info"
          :canScale="option.canScale"
          :autoCrop="option.autoCrop"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
        >
        </VueCropper>
        <br/>
        <div class="mb10">
        <span> 宽度: </span> <el-input v-model="option.autoCropWidth" size="small" placeholder="裁剪宽度" style="width: 100px;"></el-input>
        <span class="ml10"> 高度: </span><el-input v-model="option.autoCropHeight" size="small"  placeholder="裁剪高度" style="width: 100px;"></el-input>
        <span class="ml10">(原图片尺寸:{{cropWidth}} * {{cropHeight}})</span>
        </div>
        <el-button type="primary" @click="onCubeImg()">生成图片</el-button>
        <el-button @click="isShowCropper = false">取消</el-button>
    </el-dialog>
  </div>
</template>
<script>
import {getFileUrl, uploadFile} from "@/api/homeApi";
import {getToken} from '@/utils/auth'
import { VueCropper } from "vue-cropper";
export default {
  components: {
      VueCropper
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      idCardImgUrls: [],
      uploadUrl: process.env.VUE_APP_BASE_API + "/private/file/v1/upload", // 上传的图片服务器地址
      headers: {
        Authorization: getToken()
      },
      isShowCropper: false,
      cropWidth: 0,
      cropHeight: 0,
      option: {
        img: '',                         // 裁剪图片的地址
        info: true,                      // 裁剪框的大小信息
        outputSize: 1,                   // 裁剪生成图片的质量
        outputType: 'png',               // 裁剪生成图片的格式
        canScale: false,                 // 图片是否允许滚轮缩放
        autoCrop: true,                  // 是否默认生成截图框
        autoCropWidth: 300,              // 默认生成截图框宽度
        autoCropHeight: 300,             // 默认生成截图框高度
        fixed: false,                    // 是否开启截图框宽高固定比例
        fixedNumber: [4, 4],             // 截图框的宽高比例
      },
    }
  },
  props: {
    supportType: {//支持上传文件的格式
      default: () => ['image/jpeg', 'image/jpg', 'image/png'],
      type: Array
    },
    limit: {
      type: Number,
      default: 1
    },
    fileSize: {
      type: Number,
      default: 10
    },
    showFile: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    loadImageAndSetCropSize() {
        const img = new Image();
        img.src = this.option.img; // 你的图片URL
        img.onload = () => {
          // 图片加载完成，获取其原始尺寸
          this.cropWidth = img.width
          this.cropHeight = img.height

          // 设置宽高比为1:1
          const aspectRatio = 1;

          if (img.height >= 600) {
            this.option.autoCropHeight = 600;
            this.option.autoCropWidth = parseInt(600 * aspectRatio);
          } else {
            this.option.autoCropHeight = img.height;
            this.option.autoCropWidth = parseInt(img.height * aspectRatio);
          }
          // if(img.height>=800){
          //   this.option.autoCropWidth = parseInt((img.width/img.height)*800)
          //   this.option.autoCropHeight = 800
          //   console.log('autoCropWidth:',this.option.autoCropWidth);
          // } else{
          //   this.option.autoCropWidth = img.width
          //   this.option.autoCropHeight = img.height
          // }
          // 你可能还需要调用VueCropper的某个方法来刷新裁剪框大小
          // 这取决于VueCropper的具体实现和API
        };
    },
    // 上传前校检格式和大小
    beforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      // 校验上传文件格式
      if (this.supportType.indexOf(file.type) == -1) {
        let supportType = this.supportType;
        let msg = '';
        supportType.map(res => {
          msg += res.substring(6) + '/';
        });
        let newMsg = msg.slice(0, msg.length - 1);
        this.$message.error(`请上传正确的图片格式！支持的格式有：` + newMsg);
        return false;
      }
      console.log('file:',file);
      this.option.img = URL.createObjectURL(file);
      console.log('option.img:',this.option);
      this.option.autoCropWidth = this.width;
      this.option.autoCropHeight = this.height;
      this.isShowCropper = true;
      this.$nextTick(() => {
        this.option.autoCropWidth = 300;
        this.option.autoCropHeight = 300;
        this.loadImageAndSetCropSize()
      });
      return true;
    },
    // 确定裁剪图片
    onCubeImg() {
      // 获取cropper的截图的base64 数据
      this.$refs.cropper.getCropData(data => {
        this.isShowCropper = false
        // 先将显示图片地址清空，防止重复显示
        this.option.img = ''
        // 将剪裁后base64的图片转化为file格式
        let file = this.convertBase64UrlToBlob(data)
        // 将剪裁后的图片执行上传
        const fileObj = file
        const form = new FormData()
        form.append('file', fileObj)
        form.append('open', true)
        uploadFile(form).then(res => {
          if (res.code == 200) {
            let data = {
              imageUrl: `${getFileUrl}${res.data.fileId}`,
              fileName: res.data.fileName,
              fileId: res.data.fileId
            }
            this.idCardImgUrls.push(data)
            this.$emit('setCardPic', this.idCardImgUrls.map(i => i.fileId))
          } else {
            this.$message.error('上传图片失败！')
          }
        })
      })
    },
    // 将base64的图片转换为file文件
    convertBase64UrlToBlob(urlData) {
      let bytes = window.atob(urlData.split(',')[1]);//去掉url的头，并转换为byte
      const options = {
        type: 'image/jpeg',
        endings: 'native',
      }
      //处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length);
      let ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      let fileName = 'img' + new Date().getTime() + '.jpg';
      return new File([ia], fileName, options)
      // return new Blob([ab], { type: 'image/png' });
    },
    pictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    removeFileList(file) {
      return new Promise((resolve, reject) => {
        let fileId = file.response.fileId
        this.$confirm(`确定要删除图片${file.name}`, '温馨提示', {
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              let index = this.idCardImgUrls.findIndex(i => i.fileId == fileId)
              this.idCardImgUrls.splice(index, 1)
              this.$emit('setCardPic', this.idCardImgUrls.map(i => i.fileId))
              done()
              resolve()
            } else {
              done()
              reject()
            }
          }
        }).then(() => {}).catch(() => {})
      })
    },
    handleExceed() {
      this.$message.error(`只能上传${this.limit}张图片`)
    },
    /*自定义上传的方法*/
    diyRequest({file, onProgress, onSuccess}) {
      /*对上传图片的大小和格式校验*/
      const isLt = file.size / 1024 / 1024 < this.fileSize
      if (this.supportType.indexOf(file.type) == -1) {
        let supportType = this.supportType
        let msg = ''
        supportType.map(res => {
          msg += res.substring(6) + '/'
        })
        let newMsg = msg.slice(0, (msg.length) - 1)
        this.$message('error', `请上传正确的图片格式！支持的格式有：` + newMsg)
        return
      }
      if (!isLt) {
        this.$message('error', `上传图片大小不能超过${this.fileSize}MB!`)
        return
      }
      const fileObj = file
      const form = new FormData()
      form.append('file', fileObj)
      form.append('open', true)
      uploadFile(form, (progress) => {
        onProgress(progress)
      }).then(res => {
        if (res.code == 200) {
          let data = {
            imageUrl: `${getFileUrl}${res.data.fileId}`,
            fileName: res.data.fileName,
            fileId: res.data.fileId
          }
          onSuccess({
            name: data.fileName,
            url: data.imageUrl,
            id: data.fileId
          })
          this.idCardImgUrls.push(data)
          this.$emit('setCardPic', this.idCardImgUrls.map(i => i.fileId))
        } else {
          this.$message.error('上传图片失败！')
        }
      }).catch(() => {
        this.$message.error('上传图片失败！')
      })
    },
    successUpload() {
    //   this.$emit('setCardPic', this.idCardImgUrls.map(i => i.fileId))
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/css/element-variables";

:deep(.el-upload) {
  border: 1px dashed $--color-primary;
  border-radius: 0;
}
:deep(.el-upload--picture-card .el-icon-plus) {
  color: $--color-primary !important;
}
</style>

